/* Uart Events Example

   This example code is in the Public Domain (or CC0 licensed, at your option.)

   Unless required by applicable law or agreed to in writing, this
   software is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
   CONDITIONS OF ANY KIND, either express or implied.
*/
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "nvs_flash.h"
#include "driver/uart.h"
#include "esp_wifi.h"
#include "esp_event.h"
#include "freertos/queue.h"
#include "esp_log.h"
#include "driver/gpio.h"
#include "nvs_flash.h"
#include "board.h"
#include "user_mqtt.h"
#include "lwip/err.h"
#include "lwip/sys.h"


#define TAG "RS485_ECHO_APP"
#define GIO "GPIO_MESSAGE"



#define BUF_SIZE        (127)
#define BAUD_RATE       115200

// Read packet timeout
#define PACKET_READ_TICS        (100 / portTICK_RATE_MS)

#define ECHO_UART_PORT          2
// Timeout threshold for UART = number of symbols (~10 tics) with unchanged state on receive pin
#define ECHO_READ_TOUT          (3) // 3.5T * 8 = 28 ticks, TOUT=3 -> ~24..33 ticks

#define ESP_INTR_FLAG_DEFAULT 0

static TaskHandle_t led_task_handles;

static xQueueHandle gpio_evt_queue = NULL;

int timemsg[5]={0,0,0,0,0};
char msg[8] = {'0', '0'};
char out_set_flag=0;

#define EXAMPLE_ESP_WIFI_SSID      "Adkins"
#define EXAMPLE_ESP_WIFI_PASS      "denghong123"
#define EXAMPLE_ESP_MAXIMUM_RETRY  5

/* FreeRTOS event group to signal when we are connected*/
static EventGroupHandle_t s_wifi_event_group;

/* The event group allows multiple bits for each event, but we only care about two events:
 * - we are connected to the AP with an IP
 * - we failed to connect after the maximum amount of retries */
#define WIFI_CONNECTED_BIT BIT0
#define WIFI_FAIL_BIT      BIT1

static const char *WIFI = "wifi station";

const int uart_num = ECHO_UART_PORT;

static int s_retry_num = 0;

static void event_handler(void* arg, esp_event_base_t event_base,
                                int32_t event_id, void* event_data)
{
    if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_START) {
        esp_wifi_connect();
    } else if (event_base == WIFI_EVENT && event_id == WIFI_EVENT_STA_DISCONNECTED) {
        if (s_retry_num < EXAMPLE_ESP_MAXIMUM_RETRY) {
            esp_wifi_connect();
            s_retry_num++;
            ESP_LOGI(WIFI, "retry to connect to the AP");
        } else {
            xEventGroupSetBits(s_wifi_event_group, WIFI_FAIL_BIT);
        }
        ESP_LOGI(TAG,"connect to the AP fail");
    } else if (event_base == IP_EVENT && event_id == IP_EVENT_STA_GOT_IP) {
        ip_event_got_ip_t* event = (ip_event_got_ip_t*) event_data;
        ESP_LOGI(WIFI, "got ip:" IPSTR, IP2STR(&event->ip_info.ip));
        s_retry_num = 0;
        xEventGroupSetBits(s_wifi_event_group, WIFI_CONNECTED_BIT);
    }
}

void wifi_init_sta(void)
{
    s_wifi_event_group = xEventGroupCreate();

    /*Initialize the underlying TCP/IP stack. 
    NOTE:This function should be called exactly once from application code, when the application starts up. */
    ESP_ERROR_CHECK(esp_netif_init());

    /*Create default event loop. */
    ESP_ERROR_CHECK(esp_event_loop_create_default());

	/*Creates default WIFI STA. In case of any init error this API aborts. */
    esp_netif_create_default_wifi_sta();
 
    /*Init WiFi Alloc resource for WiFi driver, such as WiFi control structure, RX/TX buffer, WiFi NVS structure etc, 
    this WiFi also start WiFi task. */
    wifi_init_config_t cfg = WIFI_INIT_CONFIG_DEFAULT();
    ESP_ERROR_CHECK(esp_wifi_init(&cfg));

    esp_event_handler_instance_t instance_any_id;
    esp_event_handler_instance_t instance_got_ip;
    ESP_ERROR_CHECK(esp_event_handler_instance_register(WIFI_EVENT,
                                                        ESP_EVENT_ANY_ID,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_any_id));
    ESP_ERROR_CHECK(esp_event_handler_instance_register(IP_EVENT,
                                                        IP_EVENT_STA_GOT_IP,
                                                        &event_handler,
                                                        NULL,
                                                        &instance_got_ip));

    wifi_config_t wifi_config = {
        .sta = {
            .ssid = EXAMPLE_ESP_WIFI_SSID,
            .password = EXAMPLE_ESP_WIFI_PASS,
            /* Setting a password implies station will connect to all security modes including WEP/WPA.
             * However these modes are deprecated and not advisable to be used. Incase your Access point
             * doesn't support WPA2, these mode can be enabled by commenting below line */
	     .threshold.authmode = WIFI_AUTH_WPA2_PSK,

            .pmf_cfg = {
                .capable = true,
                .required = false
            },
        },
    };
    ESP_ERROR_CHECK(esp_wifi_set_mode(WIFI_MODE_STA) );
    ESP_ERROR_CHECK(esp_wifi_set_config(ESP_IF_WIFI_STA, &wifi_config) );
    ESP_ERROR_CHECK(esp_wifi_start() );

    ESP_LOGI(WIFI, "wifi_init_sta finished.");

    /* Waiting until either the connection is established (WIFI_CONNECTED_BIT) or connection failed for the maximum
     * number of re-tries (WIFI_FAIL_BIT). The bits are set by event_handler() (see above) */
    EventBits_t bits = xEventGroupWaitBits(s_wifi_event_group,
            WIFI_CONNECTED_BIT | WIFI_FAIL_BIT,
            pdFALSE,
            pdFALSE,
            portMAX_DELAY);

    /* xEventGroupWaitBits() returns the bits before the call returned, hence we can test which event actually
     * happened. */
    if (bits & WIFI_CONNECTED_BIT) {
        ESP_LOGI(WIFI, "connected to ap SSID:%s password:%s",
                 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
    } else if (bits & WIFI_FAIL_BIT) {
        ESP_LOGI(WIFI, "Failed to connect to SSID:%s, password:%s",
                 EXAMPLE_ESP_WIFI_SSID, EXAMPLE_ESP_WIFI_PASS);
    } else {
        ESP_LOGE(WIFI, "UNEXPECTED EVENT");
    }

    /* The event will not be processed after unregister */
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(IP_EVENT, IP_EVENT_STA_GOT_IP, instance_got_ip));
    ESP_ERROR_CHECK(esp_event_handler_instance_unregister(WIFI_EVENT, ESP_EVENT_ANY_ID, instance_any_id));
    vEventGroupDelete(s_wifi_event_group);
}


static void echo_send(const int port, const char* str, uint8_t length)
{
    if (uart_write_bytes(port, str, length) != length) {
        ESP_LOGE(TAG, "Send data critical failure.");
        // add your code to handle sending failure here
        abort();
    }
}

static void echo_task(void *arg)
{    
    uart_config_t uart_config = {
        .baud_rate = BAUD_RATE,
        .data_bits = UART_DATA_8_BITS,
        .parity = UART_PARITY_DISABLE,
        .stop_bits = UART_STOP_BITS_1,
        .flow_ctrl = UART_HW_FLOWCTRL_DISABLE,
        .rx_flow_ctrl_thresh = 122,
        .source_clk = UART_SCLK_APB,
    };

    // Set UART log level
    esp_log_level_set(TAG, ESP_LOG_INFO);

    ESP_LOGI(TAG, "Start RS485 application test and configure UART.");

    // Install UART driver (we don't need an event queue here)
    // In this example we don't even use a buffer for sending data.
    ESP_ERROR_CHECK(uart_driver_install(uart_num, BUF_SIZE * 2, 0, 0, NULL, 0));

    ESP_ERROR_CHECK(uart_param_config(uart_num, &uart_config));
    ESP_LOGI(TAG, "UART set pins, mode and install driver.");
    ESP_ERROR_CHECK(uart_set_pin(uart_num, ECHO_TEST_TXD, ECHO_TEST_RXD, ECHO_TEST_RTS, ECHO_TEST_CTS));
    ESP_ERROR_CHECK(uart_set_mode(uart_num, UART_MODE_RS485_HALF_DUPLEX));
    ESP_ERROR_CHECK(uart_set_rx_timeout(uart_num, ECHO_READ_TOUT));

    char* data = (char*) malloc(BUF_SIZE);

    memset(data,0,BUF_SIZE);

    ESP_LOGI(TAG, "UART start recieve loop.\r\n");
    echo_send(uart_num, "Start RS485 UART test.\r\n", 24);

    while(1) {
        //Read data from UART
        int len = uart_read_bytes(uart_num, data, BUF_SIZE, PACKET_READ_TICS);
        if(len>0){
            ESP_LOGI(TAG, "UART recieve data:%s\r\n",data);     
            Received_Command_Process(data);   
            memset(data,0,BUF_SIZE);    
        }
    }
    vTaskDelete(echo_task);
}

static void IRAM_ATTR gpio_isr_handler(void* arg)
{
    uint32_t gpio_num = (uint32_t) arg;
    xQueueSendFromISR(gpio_evt_queue, &gpio_num, NULL);
}


//GPIO输入监测任务
static void gpio_task(void *arg)
{
    uint32_t io_num;
    char Device_Data[1024];
    char intr_flag[4]= {'0'};
    while(1) 
    {
        if(xQueueReceive(gpio_evt_queue, &io_num, portMAX_DELAY)) {

            switch (io_num)
            {
                case 36: strcpy(intr_flag,"IN0");break;
                case 39: strcpy(intr_flag,"IN1");break;
                case 34: strcpy(intr_flag,"IN2");break;
                case 35: strcpy(intr_flag,"IN3");break;
                case 32: strcpy(intr_flag,"IN4");break;
                case 33: strcpy(intr_flag,"IN5");break;
                case 25: strcpy(intr_flag,"IN6");break;
                case 26: strcpy(intr_flag,"IN7");break;
                //default:
            }
            memset(Device_Data,0,1024);
            ESP_LOGI(GIO, "%s",intr_flag);
            sprintf(Device_Data,"Input_Port&%s,Port_Level&%d\r\n",intr_flag,gpio_get_level(io_num));
            printf("Device_data = %s \r\n",Device_Data);
            echo_send(uart_num, Device_Data, 50);
            esp_mqtt_client_publish(client, MQTT_DEVICE_DATA, Device_Data, strlen(Device_Data), 0, 0);//上报Input_Port数据
        }
    }
}

//输出任务
static void Out_set_task(void *arg)
{

    while(1)
    {
        if(out_set_flag==1)//aliyun command out set
        {
            ESP_LOGI(TAG, "OUT_PORT_DATA:%d\r\n",timemsg[0]);

            if(timemsg[0]&0x01){
                gpio_set_level(GPIO_NUM_OUT0, 1);
                ESP_LOGI(TAG, "SET_OUT0_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT0, 0);
                ESP_LOGI(TAG, "SET_OUT0_IS_0!!!\r\n");
            }

            if(timemsg[0]&0x02){
                gpio_set_level(GPIO_NUM_OUT1, 1);
                ESP_LOGI(TAG, "SET_OUT1_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT1, 0);
                ESP_LOGI(TAG, "SET_OUT1_IS_0!!!\r\n");
            }
            if(timemsg[0]&0x04){
                gpio_set_level(GPIO_NUM_OUT2, 1);
                ESP_LOGI(TAG, "SET_OUT2_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT2, 0);
                ESP_LOGI(TAG, "SET_OUT2_IS_0!!!\r\n");
            }
            if(timemsg[0]&0x08){
                gpio_set_level(GPIO_NUM_OUT3, 1);
                ESP_LOGI(TAG, "SET_OUT3_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT3, 0);
                ESP_LOGI(TAG, "SET_OUT3_IS_0!!!\r\n");
            }
            if(timemsg[0]&0x10){
                gpio_set_level(GPIO_NUM_OUT4, 1);
                ESP_LOGI(TAG, "SET_OUT4_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT4, 0);
                ESP_LOGI(TAG, "SET_OUT4_IS_0!!!\r\n");
            }
            if(timemsg[0]&0x20){
                gpio_set_level(GPIO_NUM_OUT5, 1);
                ESP_LOGI(TAG, "SET_OUT5_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT5, 0);
                ESP_LOGI(TAG, "SET_OUT5_IS_0!!!\r\n");
            }
            if(timemsg[0]&0x40){
                gpio_set_level(GPIO_NUM_OUT6, 1);
                ESP_LOGI(TAG, "SET_OUT6_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT6, 0);
                ESP_LOGI(TAG, "SET_OUT6_IS_0!!!\r\n");
            }
            if(timemsg[0]&0x80){
                gpio_set_level(GPIO_NUM_OUT7, 1);
                ESP_LOGI(TAG, "SET_OUT7_IS_1!!!\r\n");
            }
            else{
                gpio_set_level(GPIO_NUM_OUT7, 0);
                ESP_LOGI(TAG, "SET_OUT7_IS_0!!!\r\n");
            }

            out_set_flag=0;
        }
        
       vTaskDelay(20 / portTICK_PERIOD_MS); 
    }
    

}

static void Led_Task(void *pvParameters){

    while(1){

        gpio_set_level(GPIO_YELLOW_LED, 0);              //黄色指示灯亮
        vTaskDelay(500 / portTICK_PERIOD_MS);       
        gpio_set_level(GPIO_YELLOW_LED, 1);              //黄色指示灯灭
        vTaskDelay(500 / portTICK_PERIOD_MS);               
    }
}

static void gpio_num_init()
{
    //zero-initialize the config structure.
    gpio_config_t io_conf = {};
    io_conf.intr_type = GPIO_INTR_DISABLE;
    io_conf.mode = GPIO_MODE_OUTPUT;
    io_conf.pin_bit_mask = GPIO_OUTPUT_PIN_SEL;
    io_conf.pull_down_en = 1;
    io_conf.pull_up_en = 0;
    gpio_config(&io_conf);

    //interrupt of rising edge
    io_conf.intr_type = GPIO_INTR_NEGEDGE;
    io_conf.pin_bit_mask = GPIO_INPUT_PIN_SEL;
    io_conf.mode = GPIO_MODE_INPUT;
    io_conf.pull_up_en = 1;
    gpio_config(&io_conf);

    //create a queue to handle gpio event from isr
    gpio_evt_queue = xQueueCreate(10, sizeof(uint32_t));
    //start gpio task
    xTaskCreate(gpio_task, "gpio_task", 4096, NULL, 10, NULL);

    gpio_pad_select_gpio(GPIO_YELLOW_LED); 
	gpio_set_direction(GPIO_YELLOW_LED, GPIO_MODE_OUTPUT);
    xTaskCreate(Led_Task, "Led_Task", 2048, NULL, 5, &led_task_handles);

    //install gpio isr service
    gpio_install_isr_service(ESP_INTR_FLAG_DEFAULT);
    //hook isr handler for specific gpio pin
    gpio_isr_handler_add(GPIO_NUM_IN0, gpio_isr_handler, (void*) GPIO_NUM_IN0);
    gpio_isr_handler_add(GPIO_NUM_IN1, gpio_isr_handler, (void*) GPIO_NUM_IN1);
    gpio_isr_handler_add(GPIO_NUM_IN2, gpio_isr_handler, (void*) GPIO_NUM_IN2);
    gpio_isr_handler_add(GPIO_NUM_IN3, gpio_isr_handler, (void*) GPIO_NUM_IN3);
    gpio_isr_handler_add(GPIO_NUM_IN4, gpio_isr_handler, (void*) GPIO_NUM_IN4);
    gpio_isr_handler_add(GPIO_NUM_IN5, gpio_isr_handler, (void*) GPIO_NUM_IN5);
    gpio_isr_handler_add(GPIO_NUM_IN6, gpio_isr_handler, (void*) GPIO_NUM_IN6);
    gpio_isr_handler_add(GPIO_NUM_IN7, gpio_isr_handler, (void*) GPIO_NUM_IN7);

    printf("Minimum free heap size: %d bytes\n", esp_get_minimum_free_heap_size());


}



void app_main(void)
{
    //Initialize NVS
    esp_err_t ret = nvs_flash_init();  /*(NVS) Initialize the default NVS partition. */
    if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND) {
      ESP_ERROR_CHECK(nvs_flash_erase());
      ret = nvs_flash_init();
    }
    ESP_ERROR_CHECK(ret);

    ESP_LOGI(TAG, "ESP_WIFI_MODE_STA");
    wifi_init_sta();
	user_mqtt_app_start();

    gpio_num_init();

    xTaskCreate(echo_task, "uart_echo_task", 2048, NULL, 10, NULL);
    xTaskCreate(Out_set_task, "Out_set_task", 4096, NULL, 8, NULL);
}
